package com.summer.safe.utils;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.mgt.SecurityManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * Session工具类
 *
 */
public class SessionUtils {
	private static SecurityManager securityManager = SpringContextUtil.getBean(SecurityManager.class);
	private static Logger logger = LoggerFactory.getLogger(SessionUtils.class);

	/**
	 * SessionId
	 */
	public static final String SESSIONID = "sessionid";

	/**
	 * Session对象Key, 用户id
	 */
	public static final String SKEY_USER_ID = "userid";

	/**
	 * 获得Session
	 * @return
	 */
	public static Session getSession(){
		try{
			Subject subject = SecurityUtils.getSubject();
			Session session = subject.getSession(true);
			if (session == null){
				session = subject.getSession();
			}
			if (session != null){
				return session;
			}
		}catch (InvalidSessionException e){

		}
		return null;


	}



	/**
	 * 赋值session
	 * @param key
	 * @param value
	 */
	public static void setSessionAttribute(String key,  Object value){
		getSession().setAttribute(key,value);

	}
	/**
	 * 获得session
	 * @param key
	 */
	public static Object getSessionAttribute(String key){
		Object Sessionname=getSession().getAttribute(key);
		return  Sessionname;

	}

	/**
	 * 删除Session
	 * @param key
	 */
	public static void removeSessionAttribute(String key) {
		getSession().removeAttribute(key);
	}

	public static void removeAllSession() {
		String[] keys = getSessionKeys();
		if (keys != null && keys.length > 0) {
			for (String key : keys) {
				removeSessionAttribute(key);
			}
		}
	}

	public static void getAllSession() {
		String[] keys = getSessionKeys();
		if (keys != null && keys.length > 0) {
			for (String key : keys) {
				System.out.println(key);
			}
		}
	}

	public static String[] getSessionKeys() {
		logger.debug("getSessionKeys -- Thread id :{}, name : {}", Thread.currentThread().getId(), Thread.currentThread().getName());
		ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
		if (null == servletRequestAttributes) {
			return null;
		}
		return servletRequestAttributes.getAttributeNames(RequestAttributes.SCOPE_SESSION);
	}
}
